package br.cin.ufpe.in1118.middleware.distribution.services.naming.information;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import br.cin.ufpe.in1118.middleware.distribution.services.naming.gui.NamingServerMainPainel;

public class MyTree extends JTree {

	private static final long serialVersionUID = 1L;
	private NamingServerMainPainel ref = null;

	public MyTree(NamingServerMainPainel r) {
		super((Object[]) null);
		initialize();
		this.ref = r;
	}

	public void setItems(Object value) {
		TreeModel treeModel = JTree.createTreeModel(value);
		this.setModel(treeModel);
	}

	private void initialize() {
		DefaultTreeCellRenderer defaultTreeCellRenderer = new DefaultTreeCellRenderer() {
			private static final long serialVersionUID = 1L;

			public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
				JLabel retorno = new JLabel();
				
				if (value instanceof DefaultMutableTreeNode) {
					DefaultMutableTreeNode no = (DefaultMutableTreeNode) value;
					value = no.getUserObject();
					if (value instanceof ServiceInformation) {
						ServiceInformation serv = (ServiceInformation) value;
						int pingTime = serv.getPingTime();
						if (pingTime < 0) {
							retorno.setForeground(Color.red);
							retorno.setText(serv.getObjectReference().getHost());
						} else {
							retorno.setText(serv.getObjectReference().getHost() + " (" + pingTime + ")");
						}
						return retorno;
					}
				}
				return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
			}
		};
		this.setCellRenderer(defaultTreeCellRenderer);

		this.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				TreePath selPath = MyTree.this.getPathForLocation(e.getX(), e.getY());
				if (selPath != null) {
					Object value = selPath.getLastPathComponent();
					if (value instanceof DefaultMutableTreeNode) {
						DefaultMutableTreeNode no = (DefaultMutableTreeNode) value;
						value = no.getUserObject();
						if (value instanceof ServiceInformation) {
							ServiceInformation serv = (ServiceInformation) value;
							ref.exibirServInformation(serv);
						}
					}
				}
			}
		});
	}

}